package com.orange.eduservice.controller.front;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.orange.commonutils.jwt.JwtUtils;
import com.orange.commonutils.result.Result;
import com.orange.eduservice.client.OrderClient;
import com.orange.eduservice.entity.EduCourse;
import com.orange.eduservice.entity.vo.ChapterVo;
import com.orange.eduservice.entity.vo.front.CourseFrontVo;
import com.orange.eduservice.entity.vo.front.CourseWebVo;
import com.orange.eduservice.service.EduChapterService;
import com.orange.eduservice.service.EduCourseService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author orange
 * @email orangestart@yeah.net
 * @create 2021-12-26 21:08
 */
@RestController
@CrossOrigin
@RequestMapping("/eduService/courseFront")
public class CourseFrontController {

    @Autowired
    private EduCourseService eduCourseService;

    @Autowired
    private EduChapterService eduChapterService;

    @Autowired
    private OrderClient orderClient;

    //前台多条件分页查询
    @PostMapping(value = "/getConditionPage/{page}/{limit}")
    public Result pageList(@PathVariable Long page, @PathVariable Long limit,
                           @RequestBody(required = false) CourseFrontVo courseFrontVo) {

        Page<EduCourse> pageParam = new Page<>(page, limit);
        Map<String, Object> map = eduCourseService.getCourseFrontInfo(pageParam, courseFrontVo);
        return Result.ok().data(map);
    }

    //课程详情的方法
    @GetMapping("/getFrontCourseInfo/{courseId}")
    public Result getFrontCourseInfo(@PathVariable String courseId, HttpServletRequest request) {
        //是否购买课程
        boolean isBuyCourse = false;
        //根据课程id，编写sql语句查询课程信息
        CourseWebVo courseWebVo = eduCourseService.getBaseCourseInfo(courseId);
        //根据课程id，查询章节和小节信息
        List<ChapterVo> chapterVideoList = eduChapterService.getChapterVideoByCourseId(courseId);
        //获取用户id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isNotEmpty(memberId)) {
            //根据课程id、用户id，查询课程是否已经购买
            isBuyCourse = orderClient.isBuyCourse(memberId, courseId);
        }
        return Result.ok().data("courseWebVo", courseWebVo).
                data("chapterVideoList", chapterVideoList).data("isBuy", isBuyCourse);
    }
}
